package com.hssy.stationtv;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;

@SuppressLint("HandlerLeak") 
public class UpdateManager
{
	private static boolean downing = false;
	/* 下载中 */
	private static final int DOWNLOAD = 1;
	/* 下载结束 */
	private static final int DOWNLOAD_FINISH = 2;
	/* 下载保存路径 */
	private String mSavePath;
	/* 记录进度条数值 */
	private int progress;
	/* 是否取消更新 */
	private boolean cancelUpdate = false;

	private Context mContext;
	/* 更新进度 */
	private ProgressBar mProgress;
	private Dialog mDownloadDialog;
	
	MainActivity mainActivity = new MainActivity();

	private Handler mHandler = new Handler()
	{
		public void handleMessage(Message msg)
		{
			switch (msg.what)
			{
			// 正在下载
			case DOWNLOAD:
				// 设置进度条位置
				mProgress.setProgress(progress);
				break;
			case DOWNLOAD_FINISH:
				// 安装文件
				installApk();
				break;
			default:
				break;
			}
		};
	};

	public UpdateManager(Context context)
	{
		this.mContext = context;
	}

	/**
	 * 检测软件更新
	 */
	public void checkUpdate(String modularName)
	{
		if (!downing && isUpdate(modularName))
		{
			// 显示下载进度条
			downing = true;
			showDownloadDialog();
		}
	}
	
	/**
	 * 检查软件是否有更新版本
	 * 
	 * @return
	 */
	private boolean isUpdate(String modularName)
	{
		String versionName = getVerName(mContext);
		String response = "";
		try
		{
			URL url = new URL("http://192.168.1.117:9090/getRealTimeTelevisionStatus?CurrentVersion="+versionName+"&TelevisionID=" + MainActivity.TelevisionID + "&ModularName=" + modularName);
			// 创建连接
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Content-Type", "application/Json; charset=UTF-8");
			
			conn.connect();
			InputStream inputStream = conn.getInputStream();
			BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
			response = reader.readLine();
			JSONObject json = new JSONObject(response.toString());
			Map<String, String> jsonMap = new HashMap<String, String>();

			@SuppressWarnings("rawtypes")
			Iterator it = json.keys();
			while (it.hasNext()){
				String key = String.valueOf(it.next());
				String value = json.getString(key);
				jsonMap.put(key, value);
			}
			
			if(jsonMap.get("BusGradeID") != null && !jsonMap.get("BusGradeID").equals("")) {
				writeFiles(jsonMap.get("BusGradeID"), "station");
			}
			if(jsonMap.get("DataAddress") != null && !jsonMap.get("DataAddress").equals("")) {
				writeFiles(jsonMap.get("DataAddress"), "FILENAME");
			}
			if(jsonMap.get("ModularID") != null && !jsonMap.get("ModularID").equals("")) {
				writeModularName(jsonMap.get("ModularID"));
			}
			if(jsonMap.get("RestartFlag") != null && !jsonMap.get("RestartFlag").equals("") && !jsonMap.get("RestartFlag").equals("1")) {
				
			}
			if (jsonMap.get("UpgradeStatus") != null && jsonMap.get("RestartFlag").equals("YES")) {
				return true;
			}
		} catch (Exception e)
		{
			e.printStackTrace();
		}
		return false;
	}
	
//	@SuppressWarnings("deprecation")
//	public void reStart() {
//		ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
//		am.restartPackage("com.hssy.stationtv");
//	}
//	private Context mContext;
//	public void reStart() {
//		Intent k = mContext.getPackageManager()
//				.getLaunchIntentForPackage("com.hssy.stationtv");
//				k.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//				mContext.startActivity(k);
//	}
	
	@SuppressLint("SdCardPath") 
	private void writeFiles(String content, String name) {
		String fileName = "";
		if(name.equals("station")) {
			fileName = MainActivity.station;
		} else {
			fileName = MainActivity.FILENAME;
		}
        FileOutputStream outStream;
        File file = new File("/data/data/com.hssy.stationtv/files/" + fileName);
        try {
            outStream = new FileOutputStream(file);
        } catch (FileNotFoundException e) {
            return;
        }
        try {
            outStream.write(content.getBytes());
        } catch (Exception e) {
        } finally {
            try {
                outStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
	
	//修改默认加载页
	@SuppressLint("SdCardPath") 
	private void writeModularName(String content) {
        FileOutputStream outStream;
        File file = new File("/data/data/com.hssy.stationtv/files/" + MainActivity.loadPage);
        try {
            outStream = new FileOutputStream(file);
        } catch (FileNotFoundException e) {
            return;
        }
        try {
            outStream.write(content.getBytes());
        } catch (Exception e) {
        } finally {
            try {
                outStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
	}

	public String getVerName(Context context) {
        String verName = "";
        try {
            verName = context.getPackageManager().
                    getPackageInfo(context.getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return verName;
    }

	/**
	 * 显示软件下载对话框
	 */
	@SuppressLint("InflateParams") 
	private void showDownloadDialog()
	{
		// 构建软件下载对话框
		AlertDialog.Builder builder = new Builder(mContext);
		builder.setTitle(R.string.soft_updating);
		// 给下载对话框增加进度�?
		final LayoutInflater inflater = LayoutInflater.from(mContext);
		View v = inflater.inflate(R.layout.softupdate_progress, null);
		mProgress = (ProgressBar) v.findViewById(R.id.update_progress);
		builder.setView(v);
		// 取消更新
		builder.setNegativeButton(R.string.soft_update_cancel, new OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				dialog.dismiss();
				// 设置取消状
				cancelUpdate = true;
			}
		});
		mDownloadDialog = builder.create();
		mDownloadDialog.show();
		// 现在文件
		downloadApk();
	}

	/**
	 * 下载apk文件
	 */
	private void downloadApk()
	{
		// 启动新线程下载软件
		new downloadApkThread().start();
	}

	/**
	 * 下载文件线程
	 * 
	 * @author coolszy
	 *@date 2012-4-26
	 *@blog http://blog.92coding.com
	 */
	private class downloadApkThread extends Thread
	{
		@Override
		public void run()
		{
			try
			{
				// 判断SD卡是否存在，并且是否具有读写权限
				if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
				{
					// 获得存储卡的路径
					String sdpath = Environment.getExternalStorageDirectory() + "/";
					mSavePath = sdpath + "download";
					URL url = new URL("http://192.168.1.117:9090/UpgradeTelevision?TelevisionID=" + MainActivity.TelevisionID);
					// 创建连接
					HttpURLConnection conn = (HttpURLConnection) url.openConnection();
					conn.connect();
					// 获取文件大小
					int length = conn.getContentLength();
					// 创建输入
					InputStream is = conn.getInputStream();

					File file = new File(mSavePath);
					// 判断文件目录是否存在
					if (!file.exists())
					{
						file.mkdir();
					}
					File apkFile = new File(mSavePath, "StationTV.apk");
					FileOutputStream fos = new FileOutputStream(apkFile);
					int count = 0;
					// 缓存
					byte buf[] = new byte[1024];
					// 写入到文件中
					do
					{
						int numread = is.read(buf);
						count += numread;
						// 计算进度条位置
						progress = (int) (((float) count / length) * 100);
						// 更新进度
						mHandler.sendEmptyMessage(DOWNLOAD);
						if (numread <= 0)
						{
							// 下载完成
							mHandler.sendEmptyMessage(DOWNLOAD_FINISH);
							break;
						}
						// 写入文件
						fos.write(buf, 0, numread);
					} while (!cancelUpdate);// 点击取消就停止下载
					fos.close();
					is.close();
				}
			} catch (MalformedURLException e)
			{
				e.printStackTrace();
			} catch (IOException e)
			{
				e.printStackTrace();
			}
			// 取消下载对话框显示
			mDownloadDialog.dismiss();
		}
	};

	/**
	 * 安装APK文件
	 */
	private void installApk()
	{
		File apkfile = new File(mSavePath, "StationTV.apk");
		if (!apkfile.exists())
		{
			return;
		}
		try {
			URL url = new URL("http://192.168.1.117:9090/getRealTimeTelevisionStatus?TelevisionID=" + MainActivity.TelevisionID + "&UpgradeState=DOWNLOADDONE");
			// 创建连接
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Content-Type", "application/Json; charset=UTF-8");
			conn.connect();
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 通过Intent安装APK文件
		Intent i = new Intent(Intent.ACTION_VIEW);
		i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
		i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		mContext.startActivity(i);
		android.os.Process.killProcess(android.os.Process.myPid());
	}
}
